package com.lb.uts.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lb.uts.entity.JobSearch;
import com.lb.uts.entity.ScheduleJob;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 * 定时任务表 Mapper 接口
 * </p>
 *
 * @author cacframe
 * @since 2019-04-26
 */
@Repository
@Mapper
public interface ScheduleJobMapper extends BaseMapper<ScheduleJob> {
    @Select("<script>select * from schedule_job where 1=1 " +
            "<if test='jobName!=null'>and job_name = #{jobName}</if>" +
            "<if test='jobGroup!=null'>and job_group = #{jobGroup}</if>" +
            "<if test='callStatus!=null'>and job_status = #{callStatus}</if>" +
            " order by create_time desc</script>")
    List<ScheduleJob> queryByJobSearch(JobSearch jobSearch);

    /*
    查询所有正常的任务
     */
    @Select("select * from schedule_job where job_status!='2' order by create_time desc")
    List<ScheduleJob> queryUnDeleteList();

    @Update("<script>update schedule_job set run_num = run_num + #{num} " +
            "<if test='possession!=null and possession!=\"\"'>" +
            ",possession=#{possession}" +
            "</if> " +
            " where job_id  = #{jobId} " +
            "<if test='possession==null'>" +
            "and run_num + #{num}&lt;=concurrent_num and run_num + #{num}&gt;=0 and concurrent_num = #{concurrentNum}" +
            "</if>" +
            "<if test='possession!=null and possession!=\"\"'>" +
            " and ( possession=#{possession} or possession is null )" +
            "</if></script>")
    int updateRunNum(@Param("jobId") String jobId, @Param("possession") String possession, @Param("concurrentNum") Integer concurrentNum, @Param("num") int num);

    @Select("select count(1) from schedule_job where job_name = #{jobName} and job_group = #{jobGroup}")
    int selectUniqe(@Param("jobName") String jobName, @Param("jobGroup") String jobGroup);

    @Select("select * from schedule_job where job_name = #{jobName} and job_group = #{jobGroup}")
    ScheduleJob selectUniqeJob(@Param("jobName") String jobName, @Param("jobGroup") String jobGroup);

    @Update("<script>update schedule_job set run_num = run_num + #{num} " +
            "<if test='possession!=null and possession!=\"\"'>" +
            ",possession=null  " +
            "</if> " +
            "where job_id  = #{jobId} and concurrent_num = ${concurrentNum} and run_num + #{num}>=0</script>")
    int updateRunNumNoCondition(@Param("jobId") String jobId, @Param("possession") String possession, @Param("concurrentNum") Integer concurrentNum, @Param("num") int num);

    @Update("update schedule_job set possession=null where job_id = #{jobId}")
    int updatePossessionById(@Param("jobId") String jobId);
}
